import { Button, DatePicker, message, Radio, Table } from "antd";
import { connect } from "dva";
import { routerRedux } from "dva/router";
import moment from "moment";
import PropTypes from "prop-types";
import React, { PureComponent } from "react";
import enums from "../creditCar/enums";
import styles from "./index.less";
import Ellipsis from '@/components/Ellipsis';
import { getDicByKey, getDictOptionsByCode } from '@/support/common';
import MaskText from '@/components/MaskText'
// 下划线转驼峰
function toCamel(str) {
  return str.replace(/([^_])(?:_+([^_]))/g, function ($0, $1, $2) {
    return $1 + $2.toUpperCase();
  });
}

const regExpFields = {
  position_address: 'location',
  lng: 'longitude',
  lat: 'latitude',
  vehicle_owner_name: 'name',
  vehicle_owner_phone: 'phone',
  id_num: 'identity'
}
@connect((state) => ({
  menu: state.menu,
  creditCar: state.creditCar,
  warningRecord: state.warningRecord,
}))
export default class creditCarDetail extends PureComponent {
  static contextTypes = {
    authButton: PropTypes.array,
    dicData: PropTypes.any,
  };

  state = {
    vin: "",
    isEdit: false,
    detailData: {},
    statuesData: {},
    curPage: 1,
    pageSize: 10,
    total: 0,
    submitBntLading: false,
    fieldDetail: [],
    detailDataNew: [],
    tableData: [],
    riskOperateShow: false,
    riskWarnShow: false,
    filterItem: ["risk_warn_show", "risk_operate_show"],
    creditTypeOptions: [],
  };
  addPreinstall = (columns) => {
    return columns.map((i) => {
      const sameTitle = columns.some(
        (j) => j.name === i.name && i.fieldId !== j.fieldId
      );
      if (sameTitle && i.fieldId) {
        i.name = `${i.name}(预设)`;
      }
      return i;
    });
  };
  componentDidMount() {
    const vin = sessionStorage.getItem("vin");
    this.setState({ vin });
    const typeOption = sessionStorage.getItem("typeOption");
    this.setState({ creditTypeOptions: JSON.parse(typeOption)});
    this.props.dispatch({
      // 更多筛选数据
      type: "creditCar/postDataWithRes",
      payload: {
        url: "/mscreditbusiness/credit/merchant/field/scenelist?menu=credit&scene=detail",
      },
      callback: (response) => {
        if (response && response.statusCode == "0") {
          if (response.data && response.data.length > 0) {
            if (response.data.some((i) => i.column == "risk_operate_show")) {
              this.setState({ riskOperateShow: true });
              this.queryRecordList();
            }
            if (response.data.some((i) => i.column == "risk_warn_show")) {
              this.setState({ riskWarnShow: true });
              this.handleTableData();
            }
            // 脱敏字段添加正则校验类型
            let enhanceData = response.data.map(item => {
              if(regExpFields[item.column]) {
                return {
                  ...item,
                  regExpType: regExpFields[item.column]
                }
              }
              return item;
            })
            this.setState({
              fieldDetail: this.addPreinstall(
                enhanceData.filter(
                  (i) => !this.state.filterItem.some((j) => i.column == j)
                )
              ),
            });
            this.handleGetVehicleDetail(vin);
          }
        } else {
          // message.error(response.statusMessage);
        }
      },
    });
    // this.handleGetVehicleStatues(vin);
  }
  handleGetVehicleDetail = (vin) => {//查询授信车详情
    this.props.dispatch({
      type: "creditCar/postDataWithRes",
      payload: {
        url: "/mscreditbusiness/vehicle/credit/detail",
        vin: vin,
        // businessCode: "credit",
      },
      callback: (response) => {
        if (response && response.statusCode == "0") {
          const specialData = this.specialDataGenrator();
          if (response.data.overdueDate) {
            response.data.overdueDate = moment(response.data.overdueDate);
          }
          if (response.data.financeBeginDate) {
            response.data.financeBeginDate = moment(
              response.data.financeBeginDate
            ).format("YYYY-MM-DD");
          }
          if (response.data.positionDate) {
            response.data.positionDate = moment(
              response.data.positionDate
            ).format("YYYY-MM-DD HH:mm:ss");
          }
          let detailData = response.data;
          if (response.data.fenceInfo && response.data.fenceInfo.length >0) {
            let regExpKeys = Object.keys(regExpFields).map(key => toCamel(key))
            const list = response.data.fenceInfo;
          const keylist = list[0];
          const obj = {}
          for(let key in keylist){
             list.map(item =>{
                if(!obj[key]){
                  obj[key]=[];
                }
                if(item[key]){
                 obj[key].push(item[key])
                }else{
                  obj[key].push('暂无信息')
                }
             })
           }
           for(let key in obj){
            if(obj[key] && obj[key].length >0){
                const newValue = obj[key].join('/')
                if(regExpKeys.includes(key)) {
                  obj[key]= newValue
                } else {
                  obj[key]=<Ellipsis length={18} tooltip>{newValue}</Ellipsis>;
                }
            }
           }
           detailData =  Object.assign(response.data, obj);
          }
          const newDatas = this.createDetail(
            detailData,
            this.state.fieldDetail,
            specialData
          );
          this.setState({
            detailDataNew: newDatas,
            isEdit: false,
            detailData: response.data,
          });
        } else {
        }
      },
    });
  };

  createDetail = (detailData, fieldDetail, specialData) => {
    if (detailData.warnType == 2 && detailData.warnStatus == 1) {
      fieldDetail.push({
        column: "last_ack_date",
        createDate: detailData.lastAckDate,
        extra: null,
        groupName: "车辆风控信息",
        name: "车机告警最新回执时间",
        type: 1,
      });
    }

    const _cc = fieldDetail.reduce((total, currentValue) => {
      const info = detailData[toCamel(currentValue.column)];
      const speInfo = specialData.find((i) => i.column == currentValue.column);
      const item = { ...currentValue, ...speInfo, info };
      let flag = true;
      total = total.map((i) => {
        if (i.groupName == currentValue.groupName) {
          flag = false;
          i.list.push(item);
        }
        return i;
      });
      if (flag) {
        total.push({
          groupName: currentValue.groupName,
          list: [item],
        });
      }
      return total;
    }, []);
    return _cc;
  };

  // handleGetVehicleStatues = (vin) => {
  //   this.props.dispatch({
  //     type: "creditCar/getDataWithRes",
  //     payload: {
  //       url: "/third/credit/vehiclestatus",
  //       vin: vin,
  //     },
  //     callback: (response) => {
  //       if (response && response.statusCode == "0" && response.data.status) {
  //         this.setState({
  //           statuesData: response.data.status,
  //         });
  //       } else {
  //         if (response.statusCode != "0") {
  //           message.error(response.statusMessage);
  //         }
  //       }
  //     },
  //   });
  // };

  specialDataGenrator = () => {
    // 生成特殊字段
    return [
      {
        column: "limp_enable",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: [
            {
              value: "0",
              label: "不支持",
            },
            {
              value: "1",
              label: "支持",
            },
          ],
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
      },
      {
        // 实车当前状态
        column: "vhl_current_status",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: [
            {
              value: 0,
              label: "正常",
            },
            {
              value: 1,
              label: "锁车",
            },
            {
              value: 2,
              label: "跛行",
            },
            {
              value: 3,
              label: "待车辆反馈",
            },
          ],
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
        filterType: 1,
      },
      {
        column: "repayment_status",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: [
            {
              // 0-还款中；1-已逾期；2-已结清；3-融资已到期
              value: "0",
              label: "正常还款",
            },
            {
              value: "1",
              label: "已逾期",
            },
            {
              value: "2",
              label: "已结清",
            },
            {
              value: "3",
              label: "融资已到期",
            },
          ],
        },
        // filter: 9,
        nullValue: "未知",
        startVal: undefined,
        endVal: undefined,
      },
      {
        column: "risk_warn_status",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: [
            {
              // 1：预警  0或null：未预警 ；
              value: "0",
              label: "未预警",
            },
            {
              value: "1",
              label: "预警",
            },
          ],
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
      },
      {
        column: "engine_state",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: [
            {
              //  2-点火；0-熄火
              value: "0",
              label: "熄火",
            },
            {
              value: "2",
              label: "点火",
            },
            {
              value: "",
              label: "行驶中",
            },
          ],
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
      },
      {
        column: "warn_type",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: [
            {
              value: 0,
              label: "暂不支持",
            },
            {
              value: 1,
              label: "不可配置",
            },
            {
              value: 2,
              label: "可配置",
            },
          ],
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
      },
      {
        column: "warn_status",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: [
            {
              value: 0,
              label: "正常",
            },
            {
              value: 1,
              label: "车机告警",
            },
          ],
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
      },
      {
        column: "risk_status",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: [
            {
              //   0-正常行驶，1-锁车，2-跛行
              value: "0",
              label: "正常行驶",
            },
            {
              value: "1",
              label: "锁车",
            },
            {
              value: "2",
              label: "跛行",
            },
          ],
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
      },
      {
        column: "credit_type",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: this.state.creditTypeOptions,
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
      },
    ];
  };

  componentWillMount() {}

  handleOnReturn = () => {
    const backPath = sessionStorage.getItem("backPath");
    this.props.dispatch(
      routerRedux.push({
        pathname: backPath,
      })
    );
  };

  handleSubmit = () => {
    const { detailData } = this.state;
    if (!detailData.repaymentStatus && detailData.repaymentStatus != 0) {
      message.error("还款状态不能为空");
      return;
    }
    let submitData = {
      vin: [detailData.vin],
      repaymentStatus: detailData.repaymentStatus,
    };
    if (detailData.repaymentStatus === enums.repaymentStatus.overdue.value) {
      if (!detailData.overdueDate) {
        message.error("逾期起始日不能为空");
        return;
      } else {
        submitData.overdueDate = moment(detailData.overdueDate).format(
          "YYYY-MM-DD HH:mm:ss"
        );
      }
    }
    const list = []
     list.push({"vin":detailData.vin,"repayStatus":submitData.repaymentStatus,"overdueDate":submitData.overdueDate}) 
    //TODO:请求接口
    this.setState({
      submitBntLading: true,
    });
    this.props.dispatch({
      type: "creditCar/postListList",
      payload: {
        url: "/mscreditbusiness/vehicle/credit/update/repayStatus/batch",
        list
      },
      callback: (response) => {
        if (response && response.statusCode == "0") {
          message.success("修改状态成功");
          const vin = sessionStorage.getItem("vin");
          if (
            detailData.repaymentStatus === enums.repaymentStatus.closed.value
          ) {
            history.back();
          } else {
            this.handleGetVehicleDetail(vin);
          }
        } else {

        }
        this.setState({
          submitBntLading: false,
          isEdit: false,
        });
      },
    });
  };

  handleTableData = () => {//预警信息列表  ---风控预警记录分页查询
    const { curPage, pageSize } = this.state;
    const vin = sessionStorage.getItem("vin");

    this.setState({
      tableLoading: true,
    });

    let submitData = { vin, curPage, pageSize };

    this.props.dispatch({
      type: "creditCar/postObjWithRes",
      payload: {
        url: "/mscreditbusiness/vehicle/risk/warn/record/page",
        ...submitData,
      },
      callback: (response) => {
        if (response && response.statusCode == "0" && response.data) {
          if (
            response.data.rows.length === 0 &&
            response.data.pagination.current > 1
          ) {
            this.setState(
              {
                curPage: 1,
                pageSize: 10,
              },
              () => {
                this.handleTableData();
              }
            );
          } else {
            this.setState({
              tableData: response.data.rows,
              total: response.data.pagination.total,
            });
          }
        } else {
          if (response.statusCode !== "0") {
            message.error(response.statusMessage);
          }
        }
        this.setState({
          tableLoading: false,
        });
      },
    });
  };

  queryRecordList = () => {//风控操作记录列表
    const { dispatch } = this.props;
    const vin = sessionStorage.getItem("vin");
    dispatch({
       type: "warningRecord/riskResultList",
          payload: {
          url: '/mscreditbusiness/vehicle/risk/warn/result/page',
          businessCode: "credit-car-log",
          curPage: 1,
          pageSize: 10,
          vin,
      },
    });
  };

  handleTableChangeA = (page) => {//风控操作记录列表
    const { dispatch } = this.props;
    const vin = sessionStorage.getItem("vin");
    const params = {
      businessCode: "credit-car-log",
      curPage: page.current,
      pageSize: page.pageSize,
      vin,
    };
    dispatch({
     type: "warningRecord/riskResultList",
          payload: {
          url: '/mscreditbusiness/vehicle/risk/warn/result/page',
          ...params
      },
    });
  };

  render() {
    const {
      isEdit,
      detailData,
      statuesData,
      submitBntLading,
      total,
      curPage,
      pageSize,
    } = this.state;
    const {menu: { permissions }} = this.props;
    const {location: { pathname }} = this.props;
    const changeStateBtnAuth = permissions.includes(pathname + '/' + 'creditCarDetail_changeState');

    const {
      warningRecord: {
        detailLoading,
        riskResultList,
        pagination,
      },
    } = this.props;
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>
          共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条
        </span>
      ),
    };
    const columnsB = [
      {
        title: "预警时间",
        dataIndex: "riskTriggerDate",
        render: (text) => {
          if (text) {
            return moment(text).format("YYYY-MM-DD HH:mm:ss");
          }
        },
      },
      {
        title: "预警内容",
        dataIndex: "riskWarnMsg",
        render: (text) => (
          <Ellipsis length={15} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: "触发的异常事件",
        dataIndex: "riskEventContent",
        render: (text) => (
          <Ellipsis length={15} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: "已实施的管控措施",
        dataIndex: "riskControlResult",
        render: (text) => (
          <Ellipsis length={15} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: "处理状态",
        dataIndex: "dealStatus",
        render: (text, record) => {
          let findText = enums.dealStatus.array.find((e) => e.value === text);
          return findText ? findText.label : text;
        },
      },
    ];

    const paginationB = {
      showSizeChanger: true,
      total: total,
      current: curPage,
      pageSize: pageSize,
      showTotal: () => {
        return <span>共&nbsp;{total}&nbsp;条</span>;
      },
    };
    const wrningTableProps = {
      columns: columnsB,
      pagination: paginationB,
      rowKey: "sid",
      scroll: { x: "max-content" },
      // loading: tableLoading,
      dataSource: this.state.tableData,
      onChange: (pagination) => {
        this.setState(
          {
            curPage: pagination.current,
            pageSize: pagination.pageSize,
          },
          () => {
            this.handleTableData();
          }
        );
      },
    };
    const columnsA = [
      {
        title: "序号",
        dataIndex: "num",
        width: "7%",
        render: (text, record, index) => {
          return pagination.pageSize * (pagination.current - 1) + index + 1;
        },
      },
      {
        title: "执行时间",
        dataIndex: "operateTime",
        render: (text, record) => moment(text).format("YYYY-MM-DD HH:mm:ss"),
      },
      {
        title: '执行人',
        dataIndex: 'operator',
        render(val) {
          return <MaskText text={val} type="name" />;
        }
      },
      { title: "风控实施记录", dataIndex: "operationContent" },
    ];
    return (
      <div className={styles.root}>
        <div className={styles.topBtn}>
          <Button type="primary" onClick={() => this.handleOnReturn()}>
            返回
          </Button>
        </div>
        <div className={styles.midContent}>
          {this.state.detailDataNew.map((i) => (
            <div key={`groupName${i.groupName}`} className={styles.publicItem}>
              <div className={styles.itemTitle}>{i.groupName}</div>
              <div className={styles.itemContent}>
              {i.list.map((j) => (
                  <div
                    key={`list${j.column}`}
                    className={styles.itemContentRow}
                  >
                    <div className={styles.rowTitle}>{j.name}:</div>
                    {/* <div className={styles.rowValue}>{j.type == 2}</div> */}
                    <div className={styles.rowValue}>
                      {j.type == 4 &&
                        j.info &&
                        (typeof j.info == "number"
                          ? moment(j.info).format("YYYY-MM-DD")
                          : moment(j.info, "YYYY-MM-DD").format("YYYY-MM-DD"))}
                      {j.type == 5 &&
                        j.info &&
                        (typeof j.info == "number"
                          ? moment(j.info).format("HH:mm:ss")
                          : moment(j.info, "HH:mm:ss").format("HH:mm:ss"))}
                      {j.type == 6 &&
                        j.info &&
                        (typeof j.info == "number"
                          ? moment(j.info).format("YYYY-MM-DD HH:mm:ss")
                          : moment(j.info, "YYYY-MM-DD HH:mm:ss").format(
                              "YYYY-MM-DD HH:mm:ss"
                            ))}
                      {j.type == 2 &&
                        j.extra &&
                        (j.info !== null
                          ? typeof j.extra == "string"
                            ? j.info !== null
                            : j.extra.optionList.find((n) => n.value == j.info)
                            ? j.extra.optionList.find((n) => n.value == j.info)
                                .label
                            : j.info
                          : j.nullValue || "")}
                      {j.type == 7 && j.info && (
                        <a href={`${j.info}`} target="_blank">
                          {j.info}
                        </a>
                      )}
                      {j.type != 2 &&
                        j.type != 4 &&
                        j.type != 5 &&
                        j.type != 6 &&
                        j.type != 7 &&
                        (j.regExpType ? <MaskText text={j.info} type={j.regExpType} />: (j.info || j.info === 0 ? j.info : ""))}
                    </div>
                  </div>
                ))}
              </div>
            </div>
          ))}
        </div>
        <div className={styles.bottomEditState}>
          <div className={styles.title}>还款状态更新</div>
          <div className={styles.content}>
            <div className={styles.radio}>
              <span>还款状态:</span>
              {detailData.repaymentStatus ==
              enums.repaymentStatus.expire.value ? (
                "融资已到期"
              ) : (
                <>
                  <Radio.Group
                    value={detailData.repaymentStatus}
                    disabled={!isEdit}
                    onChange={(e) => {
                      detailData.repaymentStatus = e.target.value;
                      this.setState({
                        detailData: { ...detailData },
                      });
                    }}
                  >
                    {enums.repaymentStatus.array.map((radio) => {
                      if (radio.value !== enums.repaymentStatus.expire.value) {
                        return (
                          <Radio key={radio.value} value={radio.value}>
                            {radio.label}
                          </Radio>
                        );
                      }
                    })}
                  </Radio.Group>
                </>
              )}
            </div>
            {detailData.repaymentStatus ===
            enums.repaymentStatus.overdue.value ? (
              <div className={styles.datePicker}>
                <span>逾期起始日</span>
                <DatePicker
                  disabledDate={(current) => {
                    return current && current > moment().endOf("day");
                  }}
                  value={detailData.overdueDate}
                  onChange={(e) => {
                    detailData.overdueDate = e;
                    this.setState({
                      detailData: { ...detailData },
                    });
                  }}
                  disabled={!isEdit}
                />
              </div>
            ) : null}
            {detailData.repaymentStatus ===
              enums.repaymentStatus.expire.value ||
            (detailData.repaymentStatus ===
              enums.repaymentStatus.closed.value &&
              !isEdit) ? null : (
              <div className={styles.btns}>
                {isEdit ? (
                  <>
                    <Button
                      loading={submitBntLading}
                      onClick={() => this.handleSubmit()}
                      type="primary"
                    >
                      保存
                    </Button>
                    <Button
                      onClick={() => {
                        this.setState({
                          isEdit: false,
                        });
                      }}
                    >
                      取消
                    </Button>
                  </>
                ) : changeStateBtnAuth ? (
                  <Button
                    onClick={() => {
                      this.setState({
                        isEdit: true,
                      });
                    }}
                    type="primary"
                  >
                    修改
                  </Button>
                ) : null}
              </div>
            )}
          </div>
        </div>
        {this.state.riskOperateShow && (
          <div className={styles.midContent} style={{ paddingTop: "20px" }}>
            <div className={styles.publicItem}>
              <div className={styles.itemTitle}>风控操作记录列表</div>
              <div className={styles.itemContent}>
                <div
                  className={styles.itemContentRow}
                  style={{ width: "100%" }}
                >
                  <Table
                    style={{ width: "100%" }}
                    // loading={detailLoading}
                    columns={columnsA}
                    dataSource={riskResultList}
                    pagination={paginationProps}
                    onChange={this.handleTableChangeA}
                  />
                </div>
              </div>
            </div>
          </div>
        )}

        {this.state.riskWarnShow && (
          <div className={styles.midContent} style={{ paddingTop: "20px" }}>
            <div className={styles.publicItem}>
              <div className={styles.itemTitle}>预警信息列表</div>
              <div className={styles.itemContent}>
                <div
                  className={styles.itemContentRow}
                  style={{ width: "100%" }}
                >
                  <Table style={{ width: "100%" }} {...wrningTableProps} />
                </div>
              </div>
            </div>
          </div>
        )}
      </div>
    );
  }
}
